#include <stdio.h>
#include <string.h>

struct student {
    char name[20];
    int id;
    int age;
    int score;
};

void shuru(struct student p[], int n);
void shuchu(struct student s[], int n);
void find(struct student s[], int n);
void sort(struct student s[], int n);

int showAction();

int main(int argc, const char *argv[]) {
    struct student stu[5];
    int action;
    while(1) {
        action = showAction();
        if(action == 1) {
            shuru(stu, 5);

        } else if(action == 2){
            find(stu, 5);

        } else if(action == 3){
            sort(stu, 5);

        } else if(action == 4){
            shuchu(stu, 5);
        } else if(action == 5){
            break;
        }
    }
    return 0;
}

void find(struct student *p, int n) {
    int i, max = 0, maxid, tmp;
    for(i = 0; i < n; i++) {
        if(p[i].score > max) {
            max = p[i].score;
            maxid = i;
        }
    }
    printf("分数最高的学员的是：\n");
    printf("姓名  ID  年龄  分数\n");
    printf("%s%4d%4d%4d\n", p[maxid].name, p[maxid].id, p[maxid].age, p[maxid].score);
}

void sort(struct student *p, int n) {
    int i, j, sorted[n], ids[n], max=0, maxid, tmp;
    for(i = 0; i < n; i++) {
        sorted[i] = p[i].score;
        ids[i] = i;
    }
    for(i = 0; i < n; i++) {
        max = sorted[i];
        for(j = i+1; j < n; j++) {
            if(sorted[j] > max) {
                tmp = sorted[j];
                sorted[j] = sorted[i];
                sorted[i] = tmp;
                tmp = ids[j];
                ids[j] = ids[i];
                ids[i] = tmp;
                max = sorted[j];
            }
        }
    }
    printf("姓名  ID  年龄  分数\n");
    for(i = 0; i < n; i++) {
        maxid = ids[i];
        //printf("%4d\n", maxid);
        printf("%s%4d%4d%4d\n", p[maxid].name, p[maxid].id, p[maxid].age, p[maxid].score);
    }

}

void shuru(struct student *p, int n) {
    int i;
    printf("请输入5个学生的信息：\n");
    printf("姓名  ID  年龄  分数\n");
    for(i = 0; i < n; i++) {
        scanf("%s%d%d%d", p[i].name, &p[i].id, &p[i].age, &p[i].score);
    }
}

void shuchu(struct student s[], int n) {
    int i;
    for(i = 0; i < n; i++) {
        printf("%s %d %d %d\n", s[i].name, s[i].id, s[i].age, s[i].score);
    }
}

int showAction() {
    int action;
    while(1) {
        printf("请输入您要执行的动作序号：\n");
        printf("1.录入 2.查找 3. 排序 4.输出 5.退出\n");
        scanf("%d", &action);
        if(action< 1 || action > 5) {
            printf("您输入的序号有误，请重新输入\n");
        } else {
            break;
        }
    }
    return action;
}
